package com.gbase8c.dmt.db.opengauss;

import com.gbase8c.dmt.db.object.TableSpaceObject;

import com.gbase8c.dmt.model.migration.dto.DataSourceDto;
import com.gbase8c.dmt.model.migration.dto.TableSpaceDto;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@Slf4j
public class TableSpaceObjectImpl extends MetaImpl implements TableSpaceObject {

    public TableSpaceObjectImpl(DataSourceDto dataSourceDto) {
        super(dataSourceDto);
    }

    @Override
    public List<String> getNames(Map<String, Object> params) {
        return null;
    }

    @Override
    public TableSpaceDto get(String name, Map<String, Object> params) {
        return null;
    }

    @Override
    public TableSpaceDto convert(TableSpaceDto tableSpaceDto, Map<String, Object> params) {
        boolean preserveCase = tableSpaceDto.getTask().getMigrateConfig().isPreserveCase();
        String name = tableSpaceDto.getName();
        String tarName = wrap(name, preserveCase);
        tableSpaceDto.setTarName(tarName);
        if (!StringUtils.isBlank(tableSpaceDto.getTarPath())){
            tableSpaceDto.setConvertible(Boolean.TRUE);
        }else {
            tableSpaceDto.setConvertible(Boolean.FALSE);
        }

        if (tableSpaceDto.getConvertible()){
            tableSpaceDto.setConvertMsg("已完成");
        }else {
            tableSpaceDto.setConvertMsg("失败");
        }

        return tableSpaceDto;
    }

    @Override
    public String sql(TableSpaceDto tableSpaceDto, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLESPACE ").append(tableSpaceDto.getTarName());
        if (!StringUtils.isBlank(tableSpaceDto.getUseName())) {
            sb.append(" owner ").append(tableSpaceDto.getUseName());
        }
        if (!StringUtils.isBlank(tableSpaceDto.getRelative()) &&
                tableSpaceDto.getRelative().equalsIgnoreCase("t")) {
            sb.append(" relative");
        }
        sb.append(" location ").append("'").append(tableSpaceDto.getTarPath()).append("'");
        String spcMaxSize = null;
        if (!StringUtils.isBlank(tableSpaceDto.getSpcMaxSize()) && !tableSpaceDto.getSpcMaxSize().equals("0K")){
            spcMaxSize = tableSpaceDto.getSpcMaxSize();
            sb.append(" maxsize ").append("\'").append(spcMaxSize).append("\'");
        }
        if (!StringUtils.isBlank(tableSpaceDto.getSpcOptions())) {
            String spcOptions = tableSpaceDto.getSpcOptions();
            sb.append(" with(").append(spcOptions).append(") ");
        }
        sb.append(";");
        log.info(String.valueOf(sb));
        return sb.toString();
    }
}
